import os
import subprocess
import sys

# 检查Graphviz路径
graphviz_path = r'E:\Graphviz-14.0.4-win64\bin'
print(f"检查路径: {graphviz_path}")

if not os.path.exists(graphviz_path):
    print(f"❌ Graphviz路径不存在: {graphviz_path}")
else:
    print(f"✅ Graphviz路径存在: {graphviz_path}")
    
    # 列出目录中的可执行文件
    try:
        files = os.listdir(graphviz_path)
        exe_files = [f for f in files if f.endswith('.exe')]
        print(f"找到 {len(exe_files)} 个exe文件")
        dot_related = [f for f in exe_files if 'dot' in f.lower()]
        if dot_related:
            print("与dot相关的可执行文件:")
            for f in dot_related:
                print(f"  {f}")
        else:
            print("未找到与dot相关的可执行文件")
            print("所有exe文件:")
            for f in exe_files[:10]:  # 只显示前10个
                print(f"  {f}")
    except Exception as e:
        print(f"列出目录内容时出错: {e}")

# 尝试多种方式查找dot命令
dot_commands = ['dot', 'dot.exe']
found_dot = None

for cmd in dot_commands:
    try:
        # 先尝试直接运行
        result = subprocess.run([cmd, '-V'], capture_output=True, text=True, timeout=10)
        print(f"✅ 找到dot命令: {cmd}")
        print("版本信息:", result.stderr.strip())
        found_dot = cmd
        break
    except FileNotFoundError:
        print(f"❌ 未找到命令: {cmd}")
    except Exception as e:
        print(f"❌ 运行 {cmd} 时出错: {e}")

# 如果上面的方法不行，尝试完整路径
if not found_dot:
    print("\n尝试使用完整路径...")
    possible_dot_paths = [
        os.path.join(graphviz_path, 'dot.exe'),
        os.path.join(graphviz_path, 'dot.bat'),
        os.path.join(graphviz_path, 'dot.cmd')
    ]
    
    for dot_path in possible_dot_paths:
        if os.path.exists(dot_path):
            try:
                result = subprocess.run([dot_path, '-V'], capture_output=True, text=True, timeout=10)
                print(f"✅ 找到dot命令: {dot_path}")
                print("版本信息:", result.stderr.strip())
                found_dot = dot_path
                break
            except Exception as e:
                print(f"❌ 运行 {dot_path} 时出错: {e}")
        else:
            print(f"❌ 文件不存在: {dot_path}")

# 最后测试graphviz Python库
print("\n测试graphviz Python库...")
try:
    import graphviz
    print("✅ 成功导入graphviz库")
    
    if found_dot:
        # 设置环境变量
        os.environ["PATH"] += os.pathsep + graphviz_path
        print("✅ 已添加Graphviz到PATH")
        
        # 设置graphviz库使用特定的可执行文件 (兼容不同版本)
        if os.path.exists(found_dot) and not found_dot.startswith('dot'):
            try:
                # 尝试新版本API
                import graphviz.backend.execute
                graphviz.backend.execute.ENGINES['dot'] = found_dot
                print(f"✅ 已设置graphviz使用(新API): {found_dot}")
            except (ImportError, AttributeError):
                try:
                    # 尝试旧版本API
                    import graphviz.backend
                    graphviz.backend.ENGINES['dot'] = found_dot
                    print(f"✅ 已设置graphviz使用(旧API): {found_dot}")
                except (ImportError, AttributeError):
                    # 如果两种方法都不行，尝试设置executable参数
                    print(f"⚠️  无法直接设置引擎路径，将在渲染时指定完整路径")
        
        # 测试渲染
        try:
            dot = graphviz.Digraph()
            dot.node('A', 'Test')
            dot.node('B', 'Test2')
            dot.edge('A', 'B')
            
            os.makedirs('output', exist_ok=True)
            dot.render('output/test_fix', format='png', cleanup=True)
            print("✅ Graphviz渲染测试成功!")
        except Exception as e:
            print(f"❌ Graphviz渲染测试失败: {e}")
            import traceback
            traceback.print_exc()
    else:
        print("⚠️  由于未找到dot命令，跳过渲染测试")
        
except ImportError:
    print("❌ 无法导入graphviz库，请安装: pip install graphviz")
except Exception as e:
    print(f"❌ 测试graphviz库时出错: {e}")
    import traceback
    traceback.print_exc()